<script lang="ts" setup>
import type { VxeTableGridOptions } from '#/adapter/vxe-table';
import type { AiTrainingDatasetSamplesApi } from '#/api/ai/dataset/trainingDatasetSamples';

import { nextTick, ref, watch } from 'vue';

import { confirm, Page, useVbenModal } from '@vben/common-ui';
import { downloadFileFromBlobPart, isEmpty } from '@vben/utils';

import { message } from 'ant-design-vue';

import { ACTION_ICON, TableAction, useVbenVxeGrid } from '#/adapter/vxe-table';
import { downloadJsonFile } from '#/api/ai/dataset/trainingDatasetMeta';
import {
  deleteTrainingDatasetSamples,
  deleteTrainingDatasetSamplesList,
  exportTrainingDatasetSamples,
  getTrainingDatasetSamplesPage,
} from '#/api/ai/dataset/trainingDatasetSamples';
import { $t } from '#/locales';

import { useGridColumns, useGridFormSchema } from './data';
import Detail from './modules/detail.vue';
import Form from './modules/form.vue';

const props = defineProps<{
  datasetId: Number;
  versionId: Number;
}>();
const [FormModal, formModalApi] = useVbenModal({
  connectedComponent: Form,
  destroyOnClose: true,
});

const [DetailModal, detailModalApi] = useVbenModal({
  connectedComponent: Detail,
  destroyOnClose: true,
});

/** 刷新表格 */
function handleRefresh() {
  gridApi.reload();
}

/** 创建数据集数据 */
function handleCreate() {
  formModalApi.setData({}).open();
}

/** 编辑数据集数据 */
function handleEdit(row: AiTrainingDatasetSamplesApi.TrainingDatasetSamples) {
  formModalApi.setData(row).open();
}

/** 查看数据集数据 */
function handleDetail(row: AiTrainingDatasetSamplesApi.TrainingDatasetSamples) {
  detailModalApi.setData(row).open();
}

/** 删除数据集数据 */
async function handleDelete(
  row: AiTrainingDatasetSamplesApi.TrainingDatasetSamples,
) {
  const hideLoading = message.loading({
    content: $t('ui.actionMessage.deleting', [row.id]),
    duration: 0,
  });
  try {
    await deleteTrainingDatasetSamples(row.id as number);
    message.success({
      content: $t('ui.actionMessage.deleteSuccess', [row.id]),
    });
    handleRefresh();
  } finally {
    hideLoading();
  }
}

/** 批量删除数据集数据 */
async function handleDeleteBatch() {
  await confirm($t('ui.actionMessage.deleteBatchConfirm'));
  const hideLoading = message.loading({
    content: $t('ui.actionMessage.deletingBatch'),
    duration: 0,
  });
  try {
    await deleteTrainingDatasetSamplesList(checkedIds.value);
    checkedIds.value = [];
    message.success({
      content: $t('ui.actionMessage.deleteSuccess'),
    });
    handleRefresh();
  } finally {
    hideLoading();
  }
}

const checkedIds = ref<number[]>([]);
function handleRowCheckboxChange({
  records,
}: {
  records: AiTrainingDatasetSamplesApi.TrainingDatasetSamples[];
}) {
  checkedIds.value = records.map((item) => item.id!);
}

/** 导出表格 */
async function handleExport() {
  const data = await exportTrainingDatasetSamples(
    await gridApi.formApi.getValues(),
  );
  downloadFileFromBlobPart({ fileName: '数据集数据.xls', source: data });
}
/** 下载训练的json文件 */
async function handleDownloadJsonFile() {
  const formData = await gridApi.formApi.getValues();
  if (!formData.versionId) {
    message.error('请先选择版本');
    return;
  }
  if (!formData.splitType) {
    message.error('请先选择数据集划分类型');
    return;
  }
  // 获取当前日期
  const currentDate = new Date();
  const year = currentDate.getFullYear();
  const month = String(currentDate.getMonth() + 1).padStart(2, '0');
  const day = String(currentDate.getDate()).padStart(2, '0');
  const formattedDate = `${year}-${month}-${day}`;
  const data = await downloadJsonFile(
    formData.datasetId,
    formData.versionId,
    formData.versionNum,
    formData.splitType,
  );
  downloadFileFromBlobPart({
    fileName: `${formattedDate}-${formData.splitType}-样本文件.json`,
    source: data,
  });
}

const [Grid, gridApi] = useVbenVxeGrid({
  formOptions: {
    schema: useGridFormSchema(),
    // 默认关闭展开
    actionLayout: 'rowEnd',
  },
  gridOptions: {
    id: 'TrainingDatasetSamples-grid',
    columns: useGridColumns(),
    height: 'auto',
    pagerConfig: {
      enabled: true,
    },
    keepSource: true,
    proxyConfig: {
      ajax: {
        query: async ({ page }, formValues) => {
          return await getTrainingDatasetSamplesPage(
            {
              pageNo: page.currentPage,
              pageSize: page.pageSize,
              ...formValues,
            },
            false,
            false,
          );
        },
      },
    },
    rowConfig: {
      keyField: 'id',
      isHover: true,
    },
    toolbarConfig: {
      refresh: true,
      search: true,
    },
  } as VxeTableGridOptions<AiTrainingDatasetSamplesApi.TrainingDatasetSamples>,
  gridEvents: {
    checkboxAll: handleRowCheckboxChange,
    checkboxChange: handleRowCheckboxChange,
  },
});
watch(
  () => props.datasetId,
  (newVal) => {
    if (newVal) {
      nextTick(() => {
        gridApi.formApi.setFieldValue('datasetId', newVal);
      });
    }
  },
  { immediate: true },
);
watch(
  () => props.versionId,
  (newVal) => {
    if (newVal) {
      nextTick(() => {
        gridApi.formApi.setFieldValue('versionId', newVal);
      });
    }
  },
  { immediate: true },
);
</script>

<template>
  <Page auto-content-height>
    <FormModal @success="handleRefresh" />
    <DetailModal @success="handleRefresh" />
    <Grid table-title="数据集数据列表">
      <template #toolbar-tools>
        <TableAction
          :actions="[
            {
              label: '下载训练文件',
              type: 'primary',
              icon: ACTION_ICON.DOWNLOAD,
              auth: ['ai:training-dataset-meta:createJson'],
              onClick: handleDownloadJsonFile,
            },
            {
              label: $t('ui.actionTitle.create', ['数据集数据']),
              type: 'primary',
              icon: ACTION_ICON.ADD,
              auth: ['ai:training-dataset-samples:create'],
              onClick: handleCreate,
            },
            {
              label: $t('ui.actionTitle.export'),
              type: 'primary',
              icon: ACTION_ICON.DOWNLOAD,
              auth: ['ai:training-dataset-samples:export'],
              onClick: handleExport,
            },
            {
              label: $t('ui.actionTitle.deleteBatch'),
              type: 'primary',
              danger: true,
              icon: ACTION_ICON.DELETE,
              disabled: isEmpty(checkedIds),
              auth: ['ai:training-dataset-samples:delete'],
              onClick: handleDeleteBatch,
            },
          ]"
        />
      </template>

      <template #actions="{ row }">
        <TableAction
          :actions="[
            {
              label: '查看',
              type: 'link',
              icon: ACTION_ICON.VIEW,
              auth: ['ai:training-dataset-samples:query'],
              onClick: handleDetail.bind(null, row),
            },
            {
              label: $t('common.edit'),
              type: 'link',
              icon: ACTION_ICON.EDIT,
              auth: ['ai:training-dataset-samples:update'],
              onClick: handleEdit.bind(null, row),
            },
            {
              label: $t('common.delete'),
              type: 'link',
              danger: true,
              icon: ACTION_ICON.DELETE,
              auth: ['ai:training-dataset-samples:delete'],
              popConfirm: {
                title: $t('ui.actionMessage.deleteConfirm', [row.id]),
                confirm: handleDelete.bind(null, row),
              },
            },
          ]"
        />
      </template>
    </Grid>
  </Page>
</template>
